package aerouacmsla.interfazDeUsuario;

import aerouacmsla.procedimientos.BDConexion;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;

/**
 *
 * @author Marco
 */
public class DialogoCiudades extends javax.swing.JDialog {

    private String ciudad;
    private String pais;
    private String estado;
    private String id;
    private BDConexion miConexion;
    
    public DialogoCiudades(BDConexion miConexion) {
        initComponents();
        setModal(true);
        setMiConexion(miConexion);

        getMiConexion().sendSQLQuery("SELECT pais FROM ciudades");
        listaPais.setModel(llenarLista());
        listaEstado.setModel(new DefaultListModel());
        listaCiudad.setModel(new DefaultListModel());
    }

    public DialogoCiudades() {
        initComponents();
        setMiConexion(new BDConexion("localhost", "project_aerouac","root", "123456"));
        getMiConexion().sendSQLQuery("SELECT pais FROM ciudades");
        listaPais.setModel(llenarLista());
        listaEstado.setModel(new DefaultListModel());
        listaCiudad.setModel(new DefaultListModel());
    }

    public DefaultListModel llenarLista(){
        DefaultListModel lista = new DefaultListModel();
        String[] elementos = eliminarRepetidos(getMiConexion().getLastResultSetColumnStrings(1));
        if (elementos != null) {
            for (int i = 0; i < elementos.length; i++) {
                lista.addElement(elementos[i]);
            }
        }
        return lista;
    }
    public String[] eliminarRepetidos(String[] datos){
        int count = 0;
        String[] resultado = null;
        if (datos != null){
            for (int i=0; i<datos.length; i++){
                String temporal = datos[i];
                if (!temporal.equals("")) {
                    for (int j = i + 1; j < datos.length; j++) {
                        if (temporal.equalsIgnoreCase(datos[j])) {
                            datos[j] = "";
                        }
                    }
                    count++;
                }
            }
            int index = 0;
            resultado = new String[count+1];
            for (int i=0; i<datos.length; i++){
                if (!datos[i].equals("")){
                    resultado[index] = datos[i];
                    index++;
                }
            }
        }
        return resultado;
    }


    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listaPais = new javax.swing.JList();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        listaEstado = new javax.swing.JList();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        listaCiudad = new javax.swing.JList();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Seleccion de Ciudad");
        setIconImage(new javax.swing.ImageIcon(getClass().getResource("/Recursos/IconoCiudad32px.png")).getImage());
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Seleccione Pais"));

        listaPais.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        listaPais.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                listaPaisValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(listaPais);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE)
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Seleccione Estado"));

        listaEstado.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        listaEstado.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                listaEstadoValueChanged(evt);
            }
        });
        jScrollPane3.setViewportView(listaEstado);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE)
        );

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Seleccione Ciudad"));

        listaCiudad.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        listaCiudad.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                listaCiudadValueChanged(evt);
            }
        });
        jScrollPane4.setViewportView(listaCiudad);

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE)
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        if (!listaCiudad.isSelectionEmpty()) {
            setCiudad(listaCiudad.getSelectedValue().toString());
            System.out.println(getCiudad());
            System.out.println(getEstado());
            System.out.println(getPais());
            System.out.println(getId());
        }
        else {
            setCiudad("");
            setEstado("");
            setPais("");
            setId("");
        }
    }//GEN-LAST:event_formWindowClosing

    private void listaPaisValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_listaPaisValueChanged
        if (!listaPais.isSelectionEmpty() && listaPais.getSelectedValue() != null) {
            setPais(listaPais.getSelectedValue().toString());
            getMiConexion().sendSQLQuery("SELECT estado FROM ciudades WHERE pais = '" + getPais() + "';");
            listaEstado.setModel(llenarLista());
            listaCiudad.setModel(new DefaultListModel());
        }
    }//GEN-LAST:event_listaPaisValueChanged

    private void listaEstadoValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_listaEstadoValueChanged
        if (!listaEstado.isSelectionEmpty() && listaEstado.getSelectedValue() != null) {
            setEstado(listaEstado.getSelectedValue().toString());
            getMiConexion().sendSQLQuery("SELECT nombre_ciudad FROM ciudades WHERE estado = '" + getEstado() + "';");
            listaCiudad.setModel(llenarLista());
        }
    }//GEN-LAST:event_listaEstadoValueChanged

    private void listaCiudadValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_listaCiudadValueChanged
        if (!listaCiudad.isSelectionEmpty() && listaCiudad.getSelectedValue() != null) {
            setCiudad(listaCiudad.getSelectedValue().toString());
        }
        getMiConexion().sendSQLQuery("SELECT id_ciudad FROM ciudades WHERE " +
                    "nombre_ciudad = '" + getCiudad() + "' && pais = '" + getPais() + "' && " +
                    "estado = '" + getEstado() + "';");
        try {
            if (getMiConexion().getResultado().next()) {
                setId(getMiConexion().getResultado().getObject("id_ciudad").toString());
            }
        } catch (SQLException ex) {
            Logger.getLogger(DialogoCiudades.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_listaCiudadValueChanged

    public String getCiudad() {
        return ciudad;
    }

    public void setCiudad(String ciudad) {
        this.ciudad = ciudad;
    }

    public String getEstado() {
        return estado;
    }

    public void setEstado(String estado) {
        this.estado = estado;
    }

    public String getPais() {
        return pais;
    }

    public void setPais(String pais) {
        this.pais = pais;
    }

    public void setMiConexion(BDConexion miConexion) {
        this.miConexion = miConexion;
    }

    public BDConexion getMiConexion() {
        return miConexion;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
    
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new DialogoCiudades().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JList listaCiudad;
    private javax.swing.JList listaEstado;
    private javax.swing.JList listaPais;
    // End of variables declaration//GEN-END:variables

}
